#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define Max 6 //最大定点数
#define INF 32767

typedef struct
{
    int id;
} VertexType; //顶点类型

typedef struct
{
    int edges[Max][Max]; //邻接矩阵
    int n;               //顶点变数
    int e;               //变数
} MatGraph;              //邻接矩阵图

typedef struct Anode
{
    int adjnode_id; //相邻节点编号
    struct Anode *next_adjnode;
    int weight; //权
} ArcNode;      //边节点类型

typedef struct Vnode
{
    ArcNode *first_node;
} HeadNode; //头节点类型

typedef struct
{
    HeadNode adjList[Max]; //邻接表头节点数组
    int n;
    int e;
} AdjGraph; //邻接表图

void CreateAdj(AdjGraph *&G, int A[Max][Max], int n, int e) //创建邻接表
{
    int i, j;
    ArcNode *p;
    G = (AdjGraph *)malloc(sizeof(AdjGraph));
    for (i = 0; i < n; i++)
    {
        G->adjList[i].first_node = NULL; //所有头节点指针域置为空
    }
    for (i = 0; i < n; i++)
        for (j = n - 1; j >= 0; j--)
        {
            if (A[i][j] != 0 && A[i][j] != INF) //存在边
            {
                p = (ArcNode *)malloc(sizeof(ArcNode));
                p->weight = A[i][j];
                p->adjnode_id = j;
                p->next_adjnode = G->adjList[i].first_node;
                G->adjList[i].first_node = p;
            }
        }
    G->n = n;
    G->e = e;
}

void Disp(AdjGraph *G) //输出邻接表图
{
    ArcNode *p;
    for (int i = 0; i < G->n; i++)
    {
        p = G->adjList[i].first_node;
        printf("%3d: ", i);
        while (p != NULL)
        {
            printf("%3d[%d]→", p->adjnode_id, p->weight);
            p = p->next_adjnode;
        }
        printf("∧\n");
    }
}

void DestoryAdj(AdjGraph *&G)
{
    ArcNode *pre, *p;
    for (int i = 0; i < G->n; i++)
    {
        pre = G->adjList[i].first_node;
        if (pre != NULL)
        {
            p = pre->next_adjnode;
            while (p != NULL)
            {
                free(pre);
                pre = p;
                p = p->next_adjnode;
            }
            free(pre);
        }
    }
    free(G);
}

int main()
{
    int map[Max][Max] = {{0, 5, INF, 7, INF, INF},
                         {INF, 0, 4, INF, INF, INF},
                         {8, INF, 0, INF, INF, 9},
                         {INF, INF, 5, 0, INF, 6},
                         {INF, INF, INF, 5, 0, INF},
                         {3, INF, INF, INF, 1, 0}};
    for (int i = 0; i < Max; i++)
    {
        for (int j = 0; j < Max; j++)
            printf("%d ", map[i][j]);
        printf("\n");
    }

    AdjGraph *G;
    CreateAdj(G, map, Max, 10);
    Disp(G);
    DestoryAdj(G);
    return 0;
}
